#pragma once
#include <windows.h>
#include "device.h"
using namespace Graphic;
namespace{
	HINSTANCE G_INSTANCE = 0;

	const int SHOW_X		= 100;
	const int SHOW_Y		= 50;
	const int WIN_WIDTH		= 800;
	const int WIN_HEIGHT	= 600;

	const wchar_t* WND_CLASS_NAME = L"DEVICE_TEST_WIN_CLASS";
	const wchar_t* WND_TITLE_NAME = L"Device Test";

	Device* s_pDeivce = 0;
}

void RegWinClass();
HWND CreateWin();
int MainLoop();
void Initial(){}
void Deinit();
LRESULT CALLBACK MainWindowProc(HWND, UINT, WPARAM, LPARAM);


int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd)
{
	
	G_INSTANCE = hInst;
	RegWinClass();
	HWND hWindow = CreateWin();

	CreateParam cp;
	cp.WindowHandle = hWindow;
	s_pDeivce = CreateDevice(cp);

	//Program* pProg = new Program;

	Initial();
	int rCode = MainLoop();
	Deinit();
	//delete pProg;
	return rCode;
}

void RegWinClass()
{
	WNDCLASS wndClass;
	memset(&wndClass,0,sizeof(WNDCLASS));
	wndClass.hInstance = G_INSTANCE;
	wndClass.lpfnWndProc = MainWindowProc;
	wndClass.lpszClassName = WND_CLASS_NAME;
	wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	::RegisterClass(&wndClass);
}

int MainLoop()
{
	MSG msg;
	while(1)
	{
		::PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
		if(msg.message == WM_QUIT)
		{
			break;
		}
		::TranslateMessage(&msg);
		::DispatchMessage(&msg);
		
		s_pDeivce->Clear(GetXRGB(100,100,255));
		s_pDeivce->Present();
	}
	return 0;
}

HWND CreateWin()
{
	HWND hWindow =  CreateWindow(
		WND_CLASS_NAME,
		WND_TITLE_NAME,
		WS_POPUP | WS_VISIBLE,
		SHOW_X, SHOW_Y,
		WIN_WIDTH, WIN_HEIGHT,
		0, 0, G_INSTANCE, 0
	);
	ShowWindow(hWindow, SW_NORMAL);
	UpdateWindow(hWindow);
	return hWindow;
}

LRESULT CALLBACK MainWindowProc( HWND hWindow, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
	switch(uMessage)
	{
	case WM_CHAR:
		switch(wParam)
		{
		case VK_ESCAPE:
			SendMessage(hWindow, WM_CLOSE, 0, 0);
			return 0;
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWindow, uMessage, wParam, lParam);
}

void Deinit()
{
	UnregisterClass(WND_CLASS_NAME, G_INSTANCE);
	s_pDeivce->Release();
}